package com.tgy.programmer_code_interview_guide._02_linkedList;

import com.tgy.leetcode.ListNode;

/**
 * @Author: tgy
 * @Date: 1/27/21 10:51 AM
 */
public class _10_单链表K个节点之间逆序 {

    public static ListNode reversalK(ListNode head, int k){

        if (head == null || head.next == null || k <= 1) {

            return head;
        }

        ListNode dummyNode = new ListNode(0);
        ListNode tailNode = dummyNode;
        ListNode node = head;
        ListNode startNode = null,endNode = null;
        int index = 0;

        while (node != null) {


            if (index == k-1) {
                index = 0;
                ListNode nextNode = node.next;
                reversal(startNode,nextNode);
                tailNode.next = node;
                tailNode = startNode;
                node = nextNode;
                continue;
            }

            if (index == 0) {

                startNode = node;
            }
            node = node.next;
            index++;
        }

        if (index != 0) {

            tailNode.next = startNode;
        }
        return dummyNode.next;
    }

    public static void reversal(ListNode startNode, ListNode endNode) {

        ListNode preNode = null,curNode = startNode,nextNode = null;

        while (curNode != endNode) {

            nextNode = curNode.next;
            curNode.next = preNode;
            preNode = curNode;
            curNode = nextNode;
        }
    }

    public static void main(String[] args) {

        ListNode root = ListNode.general(new int[]{1, 2, 3, 4, 5, 6});

        ListNode reversalRoot = reversalK(root, 7);

        ListNode.printListNode(reversalRoot);
    }
}
